from random import randint
from itertools import islice
from shutil import copytree
from video_compressor import THREAD_POOL
from video_compressor import printf
from video_compressor import Colors
from video_compressor import VIDEO_WIDE
from video_compressor import VIDEO_HIGH
from video_compressor import IN_DIR_PATH
from video_compressor import OUT_DIR_PATH
from video_compressor import VIDEO_EXTS
from video_compressor import MIN_FILE
from video_compressor import MAX_FILE
from video_compressor.utils import get_video_info
from video_compressor.ffmpeg_video import ffmpy_gpu_video_xfade
from video_compressor.ffmpeg_video import run


def get_tasks():
    tasks = []
    for dir in filter(lambda f: f.is_dir(), IN_DIR_PATH.iterdir()):
        file_list = []
        files = [file for file in sorted(filter(lambda f: f.is_file() and f.suffix in VIDEO_EXTS, dir.iterdir()), reverse=False)]
        out_dir_path = OUT_DIR_PATH.joinpath(dir.relative_to(IN_DIR_PATH))
        if not out_dir_path.exists(): copytree(dir, out_dir_path)

        if files:
            min_file = min(MIN_FILE, len(files) - 1)
            max_file = min(MAX_FILE, 10)
            files_ = files[min_file: min_file + max_file]
            for file in files_:
                wide, high, total_time = get_video_info(file)
                printf(f'{Colors.OKGREEN}分析视频{Colors.ENDC}{Colors.OKBLUE}{file}{Colors.ENDC} {Colors.OKGREEN}{wide},{high},{total_time}{Colors.ENDC}')
                file_list.append((file, randint(0, int(total_time-10))))
        if file_list:
            wide, high, total_time = get_video_info(file_list[0][0])
            out_path = out_dir_path / f'{len(file_list[0][0].stem)*"0"}{file_list[0][0].suffix}'
            if out_path.is_file(): continue
            video_wide = VIDEO_WIDE if VIDEO_WIDE else wide
            video_high = VIDEO_HIGH if VIDEO_HIGH else high
            printf(f'{Colors.OKGREEN}创建任务{Colors.ENDC}{Colors.OKBLUE}{out_path}{Colors.ENDC} {Colors.OKGREEN}剧集前情摘要{Colors.ENDC}')
            ffmpeg = ffmpy_gpu_video_xfade(file_list, out_path=out_path, wide=video_wide, high=video_high)
            task = THREAD_POOL.submit(run, ffmpeg, out_path)
            tasks.append(task)
    return tasks

